import React from "react";
// 引入钩子
import { useSearchParams } from "react-router-dom";
// 引入类型声明文件
import type guest from "@/types/guest";
import type business from "@/types/business";

const GuestEdit = () => {
  const [form] = React.UI.Form.useForm();
  // 调用react-router-dom提供的获取地址栏参数的钩子
  const [searchParams] = useSearchParams();
  // 用户数据
  const [business] = useState<business>(React.business);
  // 获取地址栏参数
  const [gid] = React.useState(searchParams.get('gid') ? searchParams.get('gid') : 0);
  // 住客信息
  const [guestInfo, SetGuestInfo] = React.useState<guest>({} as guest);

  // 获取数据方法
  const fetchData = async () => {
    // 组装参数
    const params = {
      id: gid,
      busid: business.id
    };
    // 发起请求
    const result = await React.Http.post("/guest/info", params);
    if (result.code === 1) {
      // 将返回的数据赋值给 guestInfo
      SetGuestInfo(result.data);
      // 更新表单数据
      form.setFieldsValue(result.data);
    } else {
      React.fail(result.msg, () => {
        React.navigate(-1);
      })
    }
  }

  // 组件挂载后获取数据
  useEffect(() => {
    fetchData();
  }, []);

  // 表单提交
  const onSubmit = async (values: guest) => {
    // 组装参数
    const params = {
      ...values,
      id: gid,
      busid: business.id
    };
    // 发起请求
    const result = await React.Http.post("/guest/edit", params);
    if (result.code === 1) {
      React.success(result.msg, () => {
        // 返回上一页
        React.navigate(-1);
      });
    } else {
      React.fail(result.msg);
    }
  };

  return (
    <>
      <React.UI.Form
        form={form}
        layout="horizontal"
        onFinish={onSubmit}
        initialValues={guestInfo}
        footer={
          <React.UI.Button block type='submit' color='primary' size='large'>
            提交修改
          </React.UI.Button>
        }
      >
        <React.UI.Form.Item name="nickname" label="昵称" rules={[{ required: true }]}>
          <React.UI.Input placeholder="请输入昵称" />
        </React.UI.Form.Item>

        <React.UI.Form.Item name='mobile' label='手机号' rules={[{ required: true }, { pattern: /^1[3456789]\d{9}$/, message: '手机号格式不对' }]}>
          <React.UI.Input placeholder='请输入手机号' />
        </React.UI.Form.Item>

        <React.UI.Form.Item name="gender" label="性别" rules={[{ required: true }]}>
          <React.UI.Radio.Group>
            <React.UI.Space direction='horizontal'>
              <React.UI.Radio value='0'>女</React.UI.Radio>
              <React.UI.Radio value='1'>男</React.UI.Radio>
            </React.UI.Space>
          </React.UI.Radio.Group>
        </React.UI.Form.Item>

      </React.UI.Form>
    </>
  )
}

export default GuestEdit;